<template>
  <div class="container goods-order-container">
    <div class="order-title">确认订单</div>
    <div class="order-address" v-if="productOrderInfo.product.fictitious == 0">
      <div class="order-address__header">
        <div class="title">收货地址</div>
        <el-link type="primary" :underline="false" @click="openAddressModify">新增收货地址</el-link>
        <el-link
          class="visible"
          :class="[{ active: addressVisible }]"
          @click="handleAddressVisibleChange"
          :underline="false"
          >{{ addressVisible ? '收起' : '展开' }}<i class="el-icon-arrow-down el-icon--right"></i
        ></el-link>
        <div></div>
      </div>
      <el-scrollbar class="order-address__scrollbar">
        <div class="order-address__body">
          <div
            class="address-item address-item__default"
            :class="[
              {
                current: item.id == currentAddress,
                visible: index > 2 && !addressVisible
              }
            ]"
            v-for="(item, index) in addressList"
            :key="item"
            @click="handleCurrentAddress(item.id)"
          >
            <div class="other">
              <div class="name">{{ item.consignee }}</div>
              <div class="prominent">
                <el-link
                  type="primary"
                  :underline="false"
                  v-if="currentAddress != item.id"
                  @click.stop="handleAddressDelete(item.id)"
                  >删除</el-link
                >
                <el-link type="primary" :underline="false" @click.stop="openAddressModify(item)"
                  >修改</el-link
                >
                <el-link
                  type="info"
                  :underline="false"
                  v-if="item.id != defaultAddress"
                  @click.stop="handleAddressDefault(item.id)"
                  >设为默认</el-link
                >
              </div>
              <div class="default" v-if="item.id == defaultAddress">
                默认地址
              </div>
            </div>
            <div class="line"></div>
            <div class="phone">{{ item.phone }}</div>
            <div class="location">
              <i class="el-icon-location-outline el-icon--left"></i>
              <span class="bold">{{ item.areatext }}</span>
              {{ item.address }}
            </div>
            <div class="tag" v-if="item.id == currentAddress">
              <div class="triangle"></div>
              <i class="check el-icon-check"></i>
            </div>
          </div>
          <div
            class="address-item address-item__add"
            :class="[
              {
                visible: addressList.length > 2 && !addressVisible
              }
            ]"
            @click="openAddressModify"
          >
            <i class="el-icon-plus"></i>
            <div class="name">新增收货地址</div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="order-product__header">
      <span class="text">商品详情</span>
      <span class="text">售价</span>
    </div>
    <div class="order-product__body">
      <div class="product-title">商品详情</div>
      <div class="product-group">
        <div class="picture">
          <edu-image class="image" :src="productOrderInfo.product.cover_url"></edu-image>
        </div>
        <div class="desc">
          <h3 class="title">
            {{ productOrderInfo.product.title }}
          </h3>
          <!-- <div class="aging">永久有效</div> -->
        </div>
        <div class="amount">
          <div
            class="price"
            v-if="productOrderInfo.product.credit_price && productOrderInfo.product.cash_price > 0"
          >
            {{ productOrderInfo.product.credit_price }}积分+{{
              productOrderInfo.product.cash_price | formatMoney
            }}
          </div>
          <div class="price" v-else-if="productOrderInfo.product.credit_price > 0">
            {{ productOrderInfo.product.credit_price }}积分
          </div>
          <div class="price" v-else-if="productOrderInfo.product.cash_price > 0">
            {{ productOrderInfo.product.cash_price | formatMoney }}
          </div>
          <div class="free" v-else>免费</div>
          <div class="money">运费：{{ productOrderInfo.product.carriage | formatMoney }}</div>
          <el-input-number
            size="mini"
            v-model="productQuantity"
            :min="1"
            :max="99"
            @change="handleNumberChange"
          ></el-input-number>
        </div>
      </div>
    </div>
    <div class="order-product__coupon">
      <div class="coupon-title">
        积分<el-popover placement="right" width="200" trigger="hover">
          <div class="popover-content">
            <p>1，订单可使用积分+现金支付；</p>
            <p>2，订单抵扣积分不能超过商品最高积分抵扣数量；</p>
            <p>3，{{ productOrderInfo.credit.ratio }}积分抵扣1元。</p>
          </div>
          <i class="edu-icon-explain_icon edu-icon--right" slot="reference"></i
        ></el-popover>
      </div>
      <div class="coupon-group">
        <el-checkbox v-model="productCredit" @change="handleCheckboxChange"></el-checkbox>
        <span class="text"
          >共{{ productOrderInfo.credit.user_credit }}，本次可用{{ payCredit }}</span
        >
      </div>
    </div>
    <div class="order-line">
      <el-divider></el-divider>
    </div>
    <div v-if="!loading" class="order-product__footer">
      <span class="label">合计</span>
      <span class="price">{{ payPrice | formatMoney }}</span>
      <el-button type="primary" size="medium" :disabled="disabled" @click="submitProductOrder"
        >提交订单</el-button
      >
    </div>

    <el-dialog
      :title="`${updateAddress ? '修改' : '新增'}收货地址`"
      v-if="editorAddressVisible"
      :visible="editorAddressVisible"
      width="530px"
      :close-on-click-modal="false"
      :before-close="closeAddressModify"
      custom-class="order-address-dialog"
    >
      <el-form
        ref="addressForm"
        :rules="addressFormRules"
        :model="addressForm"
        label-width="85px"
        size="mini"
      >
        <el-form-item label="收货人姓名" prop="consignee">
          <el-input v-model="addressForm.consignee" placeholder="请填写收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请填写收货人手机号"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="areacode">
          <el-cascader
            ref="region"
            v-model="addressForm.areacode"
            :options="addressData"
            placeholder="请选择地区"
            value="code"
            label="name"
            :props="{ value: 'code', label: 'name' }"
            @change="handleRegionChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="addressForm.address"
            :minlength="1"
            :maxlength="100"
            :showWordLimit="true"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item prop="default">
          <el-checkbox v-model="addressForm.default" :true-label="1" :false-label="0"
            >设为默认地址</el-checkbox
          >
        </el-form-item>
        <div class="el-row--flex is-justify-center ">
          <el-button size="mini" @click="closeAddressModify">取消</el-button>
          <el-button
            type="primary"
            size="mini"
            :disabled="disabled"
            @click="submitAddressForm('addressForm')"
            >保存</el-button
          >
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import addressData from '@/utils/Area.json'
import { mapMutations } from 'vuex'
const defaultValueRef = () => ({
  consignee: '',
  phone: '',
  areacode: [],
  areatext: '',
  address: '',
  default: 0
})
export default {
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!this.$util.mobile(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    return {
      addressData, // 地址数据
      defaultAddress: 0, // 默认地址id
      currentAddress: 0, // 当前选择的地址id
      updateAddress: 0, // 修改地址id
      addressVisible: false, // 地址展开可见性
      editorAddressVisible: false, // 编辑地址可见性
      addressList: [], // 地址列表
      addressForm: defaultValueRef(),
      addressFormRules: {
        consignee: [
          {
            required: true,
            min: 1,
            message: '请填写正确收货人姓名',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePhone
          }
        ],
        areacode: [
          {
            type: 'array',
            required: true,
            message: '请选择地区',
            trigger: 'change'
          }
        ],
        address: [
          {
            required: true,
            min: 1,
            message: '请输入详细地址',
            trigger: 'blur'
          }
        ]
      },
      productOrderInfo: {
        address: {},
        credit: {
          user_credit: 0,
          max_credit: 0,
          arr: []
        },
        product: {
          carriage: 0,
          cash_price: 0,
          cover_url: '',
          credit_price: 0,
          fictitious: 1,
          title: ''
        }
      }, // 商品订单信息
      productQuantity: 1, // 数量
      productCredit: true, // 积分
      payCredit: 0, // 支付可用积分
      payPrice: 0, // 支付价格
      disabled: false,
      loading: true
    }
  },
  methods: {
    ...mapMutations({
      changeOrderData: 'order/SET_ORDER_DATA'
    }),
    // 获取订单信息
    getProductOrderInfo() {
      this.$api.getMallOrderFetch(
        {
          product: this.$route.query.id
        },
        res => {
          const { data } = res
          this.productOrderInfo = data
          // 地址不为空时设置默认地址
          if (!this.$util.isEmpty(data.address) && data.product.fictitious == 0) {
            this.currentAddress = data.address.id
          }
          setTimeout(() => {
            this.loading = false
            this.handleCredit()
          }, 50)
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    },
    // 商品数量发生变化时
    handleNumberChange() {
      this.handleCredit()
    },
    // 是否使用积分变化时
    handleCheckboxChange(e) {
      this.productCredit = e
      this.handleCredit()
    },
    // 计算可用积分和商品支付价格
    handleCredit() {
      let productCredit = Number(this.productOrderInfo.product.credit_price) // 单个商品的积分
      let productPrice = Number(this.productOrderInfo.product.cash_price) // 单个商品的价格
      let userCredit = Number(this.productOrderInfo.credit.user_credit) // 用户的可使用的积分
      let productCreditRatio = Number(this.productOrderInfo.credit.ratio) // 商品的积分比例
      let productCarriage = Number(this.productOrderInfo.product.carriage) // 商品运费
      let currentCredit = productCredit * this.productQuantity // 总积分
      let currentPrice = productPrice * this.productQuantity // 总价
      let credit = 0 // 支付的积分
      let price = 0 // 支付的价格
      // 是否使用积分
      if (this.productCredit) {
        // 如果用户的积分大于等于选择的总积分
        if (userCredit >= currentCredit) {
          price = currentPrice + productCarriage
          credit = currentCredit
        } else {
          // 积分不够时，计算积分的差价加上商品的价格就是支付价格，然后加上运费
          price = (currentCredit - userCredit) / productCreditRatio + currentPrice + productCarriage
          credit = userCredit
        }
      } else {
        price = currentCredit / productCreditRatio + currentPrice + productCarriage
        credit = 0
      }
      this.payCredit = credit
      this.payPrice = Math.floor(price * 100) / 100 // 不四舍五入保留两位小数
    },
    // 获取地址列表
    getAddressList() {
      this.$api.getMallAddressList(res => {
        const { data } = res
        this.addressList = data
        // 为空时
        if (this.$util.isEmpty(data)) {
          this.defaultAddress = 0
          this.currentAddress = 0
          return
        }
        if (data.length == 1) {
          this.currentAddress = data[0].id
        }
        let value = data.find(item => item.default == 1)
        this.defaultAddress = value ? value.id : 0
      })
    },
    // 处理地址可见性
    handleAddressVisibleChange() {
      if (this.addressList.length < 3) return
      this.addressVisible = !this.addressVisible
    },
    // 设置成默认地址
    handleAddressDefault(id) {
      if (id == this.defaultAddress) return
      this.defaultAddress = id
      this.$api.updateMallAddressDefault(
        {
          id: id,
          default: 1
        },
        res => {
          this.$message.success(res.msg)
          this.getAddressList()
        }
      )
    },
    // 设置当前地址
    handleCurrentAddress(id) {
      if (id == this.currentAddress) {
        this.currentAddress = 0
      } else {
        this.currentAddress = id
      }
    },
    // 删除地址
    handleAddressDelete(id) {
      this.$messageBox
        .confirm('您确定要删除该收货地址吗？', {
          title: '删除收货人信息'
        })
        .then(() => {
          this.$api.deleteMallAddress(
            {
              id: id
            },
            res => {
              this.$message.success(res.msg)
              // 删除的如果是当前选择的地址
              if (this.currentAddress == id) {
                this.currentAddress = 0
              }
              // 更新地址列表
              this.getAddressList()
            }
          )
        })
        .catch(() => {})
    },
    // 地区选择
    handleRegionChange() {
      let text = this.$refs['region'].getCheckedNodes()[0].pathLabels
      this.addressForm.areatext = text.join(' ')
    },
    // 打开编辑地址
    openAddressModify(item) {
      this.editorAddressVisible = true
      if (item.id) {
        this.updateAddress = item.id
        this.addressForm.consignee = item.consignee
        this.addressForm.phone = item.phone
        this.addressForm.areacode = item.areacode
        this.addressForm.areatext = item.areatext
        this.addressForm.address = item.address
        this.addressForm.default = item.default
      } else {
        this.updateAddress = 0
        Object.assign(this.addressForm, defaultValueRef())
      }
    },
    // 关闭编辑地址
    closeAddressModify() {
      this.editorAddressVisible = false
      this.$refs['addressForm'].resetFields()
    },
    // 修改/编辑地址
    submitAddressForm() {
      this.$refs['addressForm'].validate(valid => {
        if (valid) {
          this.disabled = true
          this.addressForm.areacode = this.addressForm.areacode.toString()
          // 修改地址
          if (this.updateAddress) {
            let params = {
              ...this.addressForm,
              id: this.updateAddress
            }
            this.$api.updateMallAddress(params, res => {
              this.closeAddressModify()
              this.$message.success(res.msg)
              // 更新地址列表
              this.getAddressList()
              setTimeout(() => {
                this.disabled = false
              }, 50)
            })
          } else {
            this.$api.addMallAddress(this.addressForm, res => {
              this.closeAddressModify()
              this.$message.success(res.msg)
              // 更新地址列表
              this.getAddressList()
              setTimeout(() => {
                this.disabled = false
              }, 50)
            })
          }
        } else {
          return false
        }
      })
    },
    // 提交商品订单
    submitProductOrder() {
      let addr_id = 0
      if (this.productOrderInfo.product.fictitious == 0) {
        if (this.$util.isEmpty(this.currentAddress)) {
          this.$message.error('请添加收货地址')
          return
        } else {
          addr_id = this.currentAddress
        }
      }
      this.disabled = true
      this.$api.createMallOrderSubmit(
        {
          id: this.$route.query.id,
          num: this.productQuantity,
          credit: this.payCredit,
          addr_id: addr_id
        },
        res => {
          const { data } = res
          // 是否需要支付
          if (data.need_pay == 1) {
            this.changeOrderData({
              order_no: data.order_no,
              payment: data.payment,
              return_url: `/mall/details?id=${this.$route.query.id}`
            })
            this.$router.push({
              path: '/buy/confirm'
            })
          } else {
            this.$message.success(res.msg)
            this.$router.go(-1)
          }
          setTimeout(() => {
            this.disabled = false
          }, 50)
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    }
  },
  created() {
    this.getProductOrderInfo()
    this.getAddressList()
  }
}
</script>

<style lang="scss" scoped>
.goods-order-container {
  margin-top: 20px;
  padding: 20px 30px 100px;
  background-color: #ffffff;
  .order-title {
    font-size: 16px;
    font-weight: 600;
    color: $text-color-import;
  }
  .order-address {
    margin-top: 30px;
    margin-bottom: 30px;
    &__header {
      display: flex;
      margin-bottom: 15px;
      .title {
        flex: 1;
        font-size: 14px;
        font-weight: 400;
        color: $text-color-import;
      }
      .visible {
        margin-left: 30px;
        .el-icon-arrow-down {
          transition: transform 0.2s;
        }
      }
      .visible.active .el-icon-arrow-down {
        transform: rotate(-180deg);
      }
    }
    &__scrollbar {
      ::v-deep .is-horizontal {
        display: none;
      }
    }
    &__body {
      max-height: 400px;
      display: grid;
      grid-row-gap: 30px;
      grid-column-gap: 30px;
      grid-template-columns: repeat(3, 1fr);
      .address-item {
        position: relative;
        border: 1px solid #e4e7ed;
        transition: border 0.2s;
        box-sizing: border-box;
        cursor: pointer;
        &.visible {
          display: none;
        }
        .other {
          display: flex;
          align-items: center;
          .default {
            margin-left: 15px;
            font-weight: 500;
            font-size: 14px;
            line-height: 1;
            color: $text-color-auxiliary;
          }
          .el-link + .el-link {
            margin-left: 15px;
          }
          .prominent {
            opacity: 0;
            transition: opacity 0.2s;
            margin-left: auto;
            line-height: 1;
          }
        }
        .line {
          border: 1px dashed #e4e7ed;
          margin-top: 18px;
        }
        .name {
          max-width: 190px;
          font-size: 15px;
          color: $text-color-import;
          line-height: 1;
          color: #303133;
          @include ellipsis();
        }
        .phone {
          margin-top: 15px;
          font-size: 15px;
          font-weight: 500;
          line-height: 1;
          color: $text-color-import;
        }
        .location {
          display: flex;
          margin-top: 15px;
          font-size: 14px;
          line-height: 20px;
          font-weight: 500;
          color: $text-color-import;
          .el-icon-location-outline {
            margin-top: 2px;
          }
          .bold {
            font-weight: 600;
          }
        }
        .tag {
          position: absolute;
          right: -1px;
          top: -1px;
          width: 20px;
          height: 20px;
          .triangle {
            width: 0;
            height: 0;
            border-top: 20px solid;
            border-left: 20px solid transparent;
            @include edu-color-primary(border-top-color);
          }
          .check {
            color: #ffffff;
            font-size: 12px;
            position: absolute;
            top: 0;
            right: 0;
          }
        }
      }
      .address-item__default {
        padding: 18px 20px;
        &.current {
          @include edu-color-primary(border-color);
        }
        &:hover {
          @include edu-color-primary(border-color);
          .prominent {
            opacity: 1;
          }
        }
      }
      .address-item__add {
        padding: 0;
        min-height: 158px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: #f7f7f7;
        .el-icon-plus {
          color: $text-color-import;
          font-size: 16px;
          font-weight: bold;
        }
        .name {
          margin-top: 20px;
        }
      }
    }
  }
  .order-product {
    &__header {
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 44px;
      padding-left: 180px;
      padding-right: 30px;
      background-color: #f6f9ff;
      font-size: 14px;
      color: $text-color-secondary;
      font-weight: 400;
    }
    &__body {
      margin-top: 30px;
      .product-title {
        font-size: 14px;
        font-weight: 400;
        color: $text-color-import;
      }
      .product-group {
        margin-top: 15px;
        display: flex;
        padding: 22px 30px 22px 18px;
        border: 1px solid #ebeef5;
        .picture {
          width: 94px;
          height: 94px;
          border-radius: 4px;
          border: 1px solid #dcdfe6;
          display: flex;
          align-items: center;
          justify-content: center;
          box-sizing: border-box;
          overflow: hidden;
          .el-image {
            width: 100%;
            height: 100%;
          }
        }
        .desc {
          margin-left: 15px;
          .title {
            max-width: 600px;
            font-size: 13px;
            font-weight: 500;
            color: $text-color-import;
            color: #303133;
            line-height: 18px;
            @include ellipsisLine(2);
            margin: 0;
          }
          .aging {
            font-size: 12px;
            font-weight: 400;
            color: #666666;
            margin-top: 46px;
          }
        }
        .amount {
          margin-left: auto;
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          .price {
            font-size: 14px;
            font-weight: 500;
            color: $text-color-price;
            margin-bottom: 10px;
          }
          .money {
            font-size: 12px;
            font-weight: 400;
            color: $text-color-secondary;
            margin-bottom: 26px;
          }
          .free {
            font-size: 14px;
            font-weight: 500;
            color: $text-color-free;
            margin-bottom: 10px;
          }
          .el-input-number--mini {
            width: 108px;
          }
          ::v-deep .el-input__inner,
          ::v-deep .el-input-number__decrease,
          ::v-deep .el-input-number__increase {
            border-radius: 0;
            background-color: #fff;
          }
        }
      }
    }
    &__coupon {
      margin-top: 50px;
      .coupon-title {
        font-size: 14px;
        font-weight: 500;
        color: $text-color-import;
        display: flex;
        align-items: center;
        .el-icon-warning-outline {
          font-size: 17px;
          color: $text-color-auxiliary;
        }
      }
      .coupon-group {
        display: flex;
        align-items: center;
        height: 44px;
        padding: 0 15px;
        margin-top: 15px;
        background-color: #f6f9ff;
        .text {
          margin-left: 10px;
          font-size: 14px;
          font-weight: 400;
          color: $text-color-import;
        }
        ::v-deep .el-checkbox__inner {
          border-radius: 100%;
        }
      }
    }
    &__footer {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .label {
        font-size: 13px;
        font-weight: 400;
        color: $text-color-secondary;
        margin-right: 25px;
      }
      .price {
        font-size: 18px;
        font-weight: 500;
        color: $text-color-price;
        margin-right: 40px;
      }
    }
  }
  .order-line {
    margin: 0 -30px;
  }

  ::v-deep .order-address-dialog {
    .el-dialog__header {
      border-bottom: 1px solid #e4e7ed;
    }
    .el-dialog__body {
      .el-form-item__label {
        font-size: 12px;
      }
      .el-input--mini .el-input__inner {
        height: 32px;
        line-height: 32px;
        border-radius: 0;
      }
      .el-button--mini {
        padding: 8px 20px;
      }
      .el-checkbox__inner {
        border-radius: 100%;
        display: block;
      }
      .el-checkbox__label {
        font-size: 13px;
        line-height: 16px;
      }
    }
  }
}

.popover-content {
  p {
    margin: 0;
    font-size: 12px;
    font-weight: 400;
    color: $text-color-secondary;
    line-height: 22px;
  }
}
</style>
